function Look(){
	this._SITE_NAME = "Dream in Game";
	this._FEEDBACK_URL = "/rest/uc/v1/mis/cs/send_feed_back";
//	this._FEEDBACK_URL = "http://192.168.0.15/uc/v1/mis/cs/send_feed_back";
}
var look = new Look();

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-36297315-1']);
_gaq.push(['_setDomainName', 'dreamingame.com']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);

$(document).ready(function(){
	try{
		$(window).hashchange(function(){
			look.loadFn();
		});
		$(window).hashchange();
	}catch(e){}

	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	jQuery.getScript(gaJsHost + "google-analytics.com/ga.js", function(){
		console.log("GA get is success");
	});
});

Look.prototype.loadFn = function(theme, type){
    var theme = look.getHashParam("theme"), type = look.getHashParam("type");
    var typeArray = type.split("_");
    publicInit.headerLoader();
    publicInit.footerLoader();
    publicInit.menuSet();

	if(jQuery.isFunction($.clearAutoSlider)){
		$.clearAutoSlider();
	}
  if (theme == "about") {
  		look.setTitle("ABOUT US - " + look._SITE_NAME);
		initLoader.aboutLoader();
	} else if (theme == "game"){
		initLoader.gameLoader();
	} else if (theme == "" || theme == "index"){
		look.setTitle(look._SITE_NAME);
		initLoader.indexLoader();
	}
}

var publicInit = {
	headerLoader : function(){
		if($("#header").children().length == 0){
			look.loadPage("#header", "html/public/header.html");
			$("#subPanelIn").html("");
			$.getJSON("json/game.json", function(data){
				$.each(data.app_list, function(i){
					$("#subPanelIn").append('<a href="#theme=game&type=game&appid=' + data.app_list[i].app_id + '">' + data.app_list[i].app_name + '</a>');
				});
			});
			
			var subHoverTimer = null;
			$(".sub_subset").bind("mouseenter", function(){
				clearTimeout(subHoverTimer);
				$(".sub_panel").show();
				$(this).addClass("high");
			}).bind("mouseleave", function(){
				var thisSubset = $(this);
				subHoverTimer = setTimeout(function(){
					$(".sub_panel").fadeOut();
					thisSubset.removeClass("high");
				}, 1000);
			});
			$(".sub_panel").bind("mouseenter", function(){
				clearTimeout(subHoverTimer);
				$(this).show();
			}).bind("mouseleave", function(){
				$(this).fadeOut();
				$(".sub_subset").removeClass("high");
			});
		}
	},
	footerLoader : function(){
		if($("#footer").children().length == 0){
			look.loadPage("#footer", "html/public/footer.html");
		}
	},
	menuSet : function(){
		if(look.getHashParam("type")){
			$("#navPanel a").removeClass("selected").each(function(){
				if(look.getHashParam("type") == look.getStringParam("type", $(this).attr("href"))){
					$(this).addClass("selected");
				}
			});
		} else {
			$("#navPanel a").removeClass("selected").first().addClass("selected");
		}
	}
}

var initLoader = {
	indexLoader: function(){
		look.loadPage("#main", "html/home.html");
		
		if($("#bannerSliderCell").length == 0){
			$("#banner").html(
				'<div class="banner_slider_cell look_box_shadow" id="bannerSliderCell">' +
				'	<a href="javascript:" class="banner_slider_left" id="bannerSliderLeftSubset">Left</a>' +
				'	<a href="javascript:" class="banner_slider_right" id="bannerSliderRightSubset">Right</a>' +
				'	<div class="banner_slider_img_cell" id="bannerSliderImgCell"></div>' +
				'</div>' +
				'<div class="banner_slider_num" id="bannerSliderNum"></div>'
			);
			
			$.getJSON("json/banner.json", function(data){
				$.each(data.list, function(i){
					var imgLink = data.list[i].link;
					if(imgLink == ""){
						imgLink = "javascript:"
					}
					$("#bannerSliderImgCell").append('<a href="' + imgLink + '" target="_blank"><img src="' + data.list[i].pic_url + '" title="' + data.list[i].title + '" /></a>');
				});
				$("#bannerSliderCell").slider({
					leftSubset: "#bannerSliderLeftSubset",
					rightSubset: "#bannerSliderRightSubset",
					imageCell: "#bannerSliderImgCell",
					numCell: "#bannerSliderNum",
					cellWidth: $("#bannerSliderImgCell").children().width(),
					autoTime: 8000,
					autoDirection:"left"
				});
			});
		}
		
		$("#allGamePlate").html("");
		$.getJSON("json/game.json", function(data){
			$.each(data.app_list, function(i){
				var iOSHtml = "", androidHtml = "";
				if((data.app_list[i].download.ipad != undefined && data.app_list[i].download.ipad != "") || (data.app_list[i].download.iphone != undefined && data.app_list[i].download.iphone != "")){
					iOSHtml = '<span class="plateform_icon ios_icon" title="iOS Support"></span>';
				}
				if(data.app_list[i].download.android != undefined && data.app_list[i].download.android != ""){
					androidHtml = '<span class="plateform_icon android_icon" title="Android Support"></span>';
				}
				$("#allGamePlate").append(
					'<div class="game_element">' +
					'	<div class="game_pic look_box_shadow look_box_corner">' +
					'		<a href="#theme=game&type=game&appid=' + data.app_list[i].app_id + '" target="_blank"><img src="' + data.app_list[i].app_main_pic + '" /></a>' +
					'	</div>' +
					'	<div class="game_name"><a href="#theme=game&type=game&appid=' + data.app_list[i].app_id + '" target="_blank">' + data.app_list[i].app_name + '</a></div>' +
					'	<div class="game_info" title="' + data.app_list[i].app_intro[0] + '">' + look.getByteVal(data.app_list[i].app_intro[0], 88) + '...</div>' +
					'	<div class="game_bottom">' +
					'		<a href="#theme=game&type=game&appid=' + data.app_list[i].app_id + '" target="_blank" class="a_as_button">more&nbsp;&gt;</a>' +
							androidHtml +
							iOSHtml +
					'	</div>' +
					'</div>'
				);
			});
			$("#allGamePlate").append('<div class="clear"></div>').children().first().addClass("first");
		});
	},
	aboutLoader: function(){
		if($("#aboutWrapper").length == 0){
			look.loadPage("#main", "html/about.html");
		}
	},
	gameLoader: function(){
		if($("#gameWrapper").length == 0){
			look.loadPage("#main", "html/game.html");
		}
		$(".sub_panel").hide();
		$.getJSON("json/game.json", function(data){
			$("#gameSliderImgCell, #gameLogo, #gameName, #gameSlogon, #gamePreview, #gamePicListIn, #gameFeature").html("");
			$("#gameIntro").children().first().nextAll().remove();
			$.each(data.app_list, function(i){
				if(data.app_list[i].app_id == look.getHashParam("appid")){
					look.setTitle(data.app_list[i].app_name + " - " + look._SITE_NAME);
					$("#gameSliderImgCell").append('<span><img src="' + data.app_list[i].app_banner.pic_url + '" title="' + data.app_list[i].app_banner.title + '" /></span>');
					$("#gameLogo").append('<img src="' + data.app_list[i].app_icon + '" />');
					$("#gameName").text(data.app_list[i].app_name);
					$("#gameSlogon").text(data.app_list[i].app_slogon);
					$("#gamePreview").append('<img src="' + data.app_list[i].app_preview.pic_url + '" title="' + data.app_list[i].app_preview.title + '" />');
					$.each(data.app_list[i].app_pic, function(j){
						$("#gamePicListIn").append('<span><img src="' + data.app_list[i].app_pic[j] + '" /></span>');
					});
					$.each(data.app_list[i].app_intro, function(j){
						$("#gameIntro").append('<p>' + data.app_list[i].app_intro[j] + '</p>');
					});
					$.each(data.app_list[i].app_feature, function(j){
						$("#gameFeature").append('<li><span>' + data.app_list[i].app_feature[j] + '</span></li>');
					});
					if(data.app_list[i].download.ipad != undefined){
						if(data.app_list[i].download.ipad != ""){
							$("#ipadCell").html('<a href="' + data.app_list[i].download.ipad + '" target="_blank" class="ipad" title="iPad[App Store]"></a>');
						}else{
							$("#ipadCell").html('<span class="ipad" title="iPad[Coming soon]"></span>');
						}
					}else{
						$("#ipadCell").html('<span class="ipad" title="iPad[Coming soon]"></span>');
					}
					if(data.app_list[i].download.iphone != undefined){
						if(data.app_list[i].download.iphone != ""){
							$("#iphoneCell").html('<a href="' + data.app_list[i].download.iphone + '" target="_blank" class="iphone" title="iPhone[App Store]"></a>');
						}else{
							$("#iphoneCell").html('<span class="iphone" title="iPhone[Coming soon]"></span>');
						}
					}else{
						$("#iphoneCell").html('<span class="iphone" title="iPhone[Coming soon]"></span>');
					}
					if(data.app_list[i].download.android != undefined){
						if(data.app_list[i].download.android != ""){
							$("#androidCell").html('<a href="' + data.app_list[i].download.android + '" target="_blank" class="android" title="Android[Download]"></a>');
						}else{
							$("#androidCell").html('<span class="android" title="Android[Coming soon]"></span>');
						}
					}else{
						$("#androidCell").html('<span class="android" title="Android[Coming soon]"></span>');
					}
				}
			});
			//反馈检测
			if(look.getHashParam("feedback") == "true"){
				var topOffset = $(".game_feedback").offset().top;
				$(window).scrollTop(topOffset);
				$("#userName").focus();
			}
		});
		Look.prototype.showInfo = {
			right : function(message){
				$("#gameFeedbackTip").html('<b class="color_green">' + message + '</b>');
			},
			error : function(message){
				$("#gameFeedbackTip").html('<b class="color_red">' + message + '</b>');
			},
			clear : function(){
				$("#gameFeedbackTip").html("");
			}
		}
		//[事件]
		$("#userName,#email,#content").val("").bind("keyup", function(){
			look.showInfo.clear();
		});
		//[事件]发送反馈
		$("#confirmSendSubset").unbind("click").bind("click", function(){
			var appid = look.getHashParam("appid"),
				userName = $.trim($("#userName").val()),
				email = $.trim($("#email").val()),
				content = $.trim($("#content").val());
			if(userName == ""){look.showInfo.error("The username cannot be empty");$("#userName").focus();return false;}
			if(email == ""){look.showInfo.error("The email cannot be empty");$("#email").focus();return false;}else{
				if(look.verifyEmail(email)){look.showInfo.error("The format of the e-mail address is incorrect");$("#email").focus();return false;}
			}
			if(content == ""){look.showInfo.error("Description of the problem cannot be empty");$("#content").focus();return false;}
			$(this).addClass("a_as_disabled");
			
			$.getJSON(look._FEEDBACK_URL + "?appid=" + appid + "&locale=en&userName=" + userName + "&email=" + email + "&description=" + content, function(data){
				if(data.code == 0){
					look.showInfo.right("Successful!");
					$("#userName,#email,#content").val("");
				}else{
					look.showInfo.error(data.message);
				}
				$("#confirmSendSubset").removeClass("a_as_disabled");
			});
		});
		//[事件]清空
		$("#clearSubset").unbind("click").bind("click", function(){
			$("#userName,#email,#content").val("");$("#userName").focus();look.showInfo.clear();
		});
	}
}

/**
 * 邮箱验证
 * @param str
 * @return
 */
Look.prototype.verifyEmail = function(str){
	var emailReg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
	return !emailReg.test(str);
}

/**
 * 获取指定的URL中的hash参数值 
 * @param {String} paramName URL参数
 * @return paramValue URL参数值
 */
Look.prototype.getHashParam = function(paramName) {
	var paramValue = "";
	var isFound = false;
	if (location.hash.indexOf("#") == 0 && location.hash.indexOf("=") > 1) {
		var arrSource = unescape(location.hash).substring(1,location.hash.length).split("&");
		i = 0;
		while (i < arrSource.length && !isFound) {
			if (arrSource[i].indexOf("=") > 0) {
				if (arrSource[i].split("=")[0].toLowerCase() == paramName.toLowerCase()) {
					paramValue = arrSource[i].split("=")[1];
					isFound = true;
				}
			}
			i++;
		}
	}
	return paramValue;
}

/**
 * 获取String中的参数值
 * @param key
 * @param source
 * @return
 */
Look.prototype.getStringParam = function(key,source){
	if (source.indexOf("#") != -1 || source.indexOf("?") != -1) {
		source = source.substr(1);
	}
	if(source){
		var arr = source.split("&");
		for (var i=0; i<arr.length; i++){
			if(arr[i].split("=")[0] == key){
				return arr[i].split("=")[1];
			}
		}
	}
}

/**
 * 返回字符串在规定字节长度内的值  
 * @param val
 * @param max
 * @return String
 */
Look.prototype.getByteVal = function(val,max) {   
	var returnValue='';
	var byteValLen=0;
	var val=val.split("");
	for (var i=0;i<val.length;i++){
		if(val[i].match(/[^\x00-\xff]/ig)!=null){
			byteValLen+=2;
		}else {
			byteValLen+=1;
		}
		if (byteValLen>max){
			break;
		}
		returnValue+=val[i];
	}
	return returnValue;
}

/**
 * 同步加载页面
 * @param {String} container 页面存放的div容器
 * @param {String} url 加载的页面URL
 * @param {String} callback 回调函数
 */
Look.prototype.loadPage = function(container,url,callback) {
	$.ajax({
		url : url,
		async : false,
		success : function(html) {
			$(container).html(html);
		},
		complete : function() {
			if(callback!=undefined){
				eval(callback);
			}
		},
		error : function(XmlHttpRequest, textStatus, errorThrown) {
			popError("<div style='width:480px;'>Load Page Error,Please<a href='javascript:window.location.reload();'>Refresh</a>，And Then Try Again。</div>");
		}
	});
}

/**
 * 分页
 * @param id 插入页码的地方
 * @param pageSize 每页数目
 * @param hashArray hash数组值
 * @param count 总数
 * @return
 */
Look.prototype.setPager = function(id,pageSize,hashArray,count){
	var theHtml="",className="";
	if(count==0 || count==undefined){
		$("#goodsPager").html(theHtml);
		return false;
	}
	var currentPager=1,pageStep=5,pageCount,beginPage,endPage;
	//分页算法
	pageCount=Math.ceil(count/pageSize);
	currentPager=parseInt(hashArray[1] ? hashArray[1] : 1);
	if(pageCount<currentPager){currentPager=pageCount;}
	if(currentPager<1){currentPager=1;}
	beginPage=(currentPager-Math.ceil(pageStep/2));
	if(beginPage<1){beginPage=1;}
	endPage=currentPager+pageStep/2;
	if(endPage>pageCount){endPage=pageCount+1;}
	
	if(currentPager==1){
		theHtml+='<a href="javascript:" class="disabled">First</a>';
		theHtml+='<a href="javascript:" class="disabled">Prev</a>';
	}else{
		theHtml+='<a href="'+hashArray[0]+'">First</a>';
		if(currentPager==2){
			theHtml+='<a href="'+hashArray[0]+'">Prev</a>';
		}else{
			theHtml+='<a href="'+hashArray[0]+"&page="+(currentPager-1)+'">Prev</a>';
		}
	}
	for(var i=beginPage;i<endPage;i++){
		if(currentPager==i){
			className="selected";
		}else{
			className="";
		}
		if(i==1){
			theHtml+='<a href="'+hashArray[0]+'" class="'+className+'">'+(i)+'</a>';
		}else{
			theHtml+='<a href="'+hashArray[0]+"&page="+i+'" class="'+className+'">'+(i)+'</a>';
		}
	}
	if(currentPager==pageCount){
		theHtml+='<a href="javascript:" class="disabled">Next</a>';
		theHtml+='<a href="javascript:" class="disabled">End</a>';
	}else{
		theHtml+='<a href="'+hashArray[0]+"&page="+(currentPager+1)+'">Next</a>';
		theHtml+='<a href="'+hashArray[0]+"&page="+pageCount+'">End</a>';
	}
	$(id).html(theHtml);
}

Look.prototype.setTitle = function(title){
	document.title = title;
	_gaq.push(['_trackEvent', 'click', 'page', title]);
}